<template>
  <el-dialog
    :title="formData.id ? '编辑部门' : '新增部门'"
    :visible="visible"
    width="30%"
    @close="closeFn"
  >
    <el-form
      ref="depForm"
      label-width="120px"
      :model="formData"
      :rules="formRules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployeeSimple"
        >
          <el-option
            v-for="item in employeesList"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartment, updateDepartment } from '@/api/department'
export default {
  filters: {},
  components: {},
  props: {
    visible: { type: Boolean, required: true },
    currentNode: { type: Object, required: true },
    originDepts: { type: Array, required: true }
  },
  data() {
    return {
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      formRules: {
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
            // console.log(rule, value)
            // validator箭头函数里的this指向当前组件实例，可以调用变量
            // rule是当前字段的校验规则，value是当前字段的值，成功就调用callback（），失败给传callback（new Error）
            // 注意：没有孩子节点就不会验证，所有根节点注意追加子节点
              let isRepeat = false
              if (this.formData.id) {
                // 编辑时判断同级节点名称不能重复
                isRepeat = this.originDepts.filter(item =>
                  item.pid === this.formData.pid && this.formData.id !== item.id
                ).some(item => item.name === value)
              } else {
                // 新增时判断子级节点的名字不能重复
                isRepeat = this.currentNode.children?.some(item => item.name === value)
              }

              isRepeat ? callback(new Error('部门名称不能重复')) : callback()
            }, trigger: 'blur'
          }],
        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' }, { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              // 直接排除不是自己，判断其他code有一样的就是重复了
              // 新增时没有id，所以item.id !== this.formData.id永远为true
              const isRepeat = this.originDepts.some(item =>
                item.code === value && item.id !== this.formData.id)
              isRepeat ? callback(new Error('部门编码不能重复')) : callback()
            }, trigger: 'blur'
          }],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' }, { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'blur' }]
      },
      employeesList: []
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  methods: {
    closeFn() {
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      this.$refs.depForm.resetFields()// 重置表单与校验
      this.$emit('update:visible', false)
    },
    async getEmployeeSimple() {
      // const res = await getEmployeeSimple()
      // console.log(res)
      this.employeesList = await getEmployeeSimple()
    },
    onSubmit() {
      this.$refs.depForm.validate(async(isOk) => {
        if (isOk) {
          // 根据有无id判断编辑还是新增
          if (this.formData.id) {
            await updateDepartment(this.formData)
          } else {
            await addDepartment({ ...this.formData, pid: this.currentNode.id })
            this.$message.success('添加成功')
          }
          // 关闭弹窗
          this.closeFn()
          // 通知父组件重新获取数据
          this.$emit('updateDepartment')
        }
      })
    }
  }
}
</script>

<style scoped>
/* 行内元素不能设置tac,转化为行内块里面的元素就可以了 */
.dialog-footer {
  width: 100%;
  text-align: center;
  display: inline-block;
}
</style>
